﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using AVCare.LMS.Util;
using System.Web.Security;
using System.Security.Principal;
using AVCare.LMS.DataAccess;
using AVCare.LMS.Models;
using AVCare.LMS.Web.Filters;
using FILEUPLOADSVRLib;

namespace Web
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，    adsfadf
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());


        }
        static FileUploadSvrClass fileServer;
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "login",
                "login",
                new { controller = "User", action = "Login" }
            );
            
            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();


            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            LanguageHelper.Init(Context);

            fileServer = new FILEUPLOADSVRLib.FileUploadSvrClass();
        }

        protected void Application_AuthorizeRequest(object sender, System.EventArgs e)
        {
            HttpApplication App = (HttpApplication)sender;
            HttpContext Ctx = App.Context; //获取本次Http请求相关的HttpContext对象
            if (Ctx.Request.IsAuthenticated) //验证过的用户才进行role的处理
            {
                FormsIdentity Id = (FormsIdentity)Ctx.User.Identity;
                FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份验证票
                string[] roles = Ticket.UserData.Split(','); //将身份验证票中的role数据转成字符串数组
                Ctx.User = new GenericPrincipal(Id, roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
            }
        }
    }
}